package com.antdesignbackend.backend.task;


import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.entity.Fee;
import com.antdesignbackend.backend.entity.Meter;
import com.antdesignbackend.backend.entity.Shop;
import com.antdesignbackend.backend.entity.entityVo.FeeVo;
import com.antdesignbackend.backend.entity.entityVo.MessageData;
import com.antdesignbackend.backend.entity.entityVo.MessageDataItem;
import com.antdesignbackend.backend.entity.entityVo.ShopVo;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 定时器计划任务等
 */

@Component
public class ScheduledTask {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private final MeterService meterService;
    private final IShopService shopService;
    private final LogicService logicService;
    private final FeeService feeService;
    private boolean ischeckDelay = true; //ischeckDelay
    private boolean ischeckMessageShop = true; //ischeckMessageShop
    private boolean ischeckOnOff = true; //ischeckOnOff

    @Autowired
    public ScheduledTask(MeterService meterService, IShopService shopService,LogicService logicService,FeeService feeService) {
        this.meterService = meterService;
        this.shopService = shopService;
        this.logicService = logicService;
        this.feeService=feeService;
    }
    /***
     * 检查断送电，欠费了就断电，没欠费就送电
     * 手动模式的不送电
     * 1分钟执行一次
     * @return
     */
     @Scheduled(cron = "0 0/1 * * * ?")
    public void checkOnOff() {
        if (!ischeckOnOff) return;
        ischeckOnOff = false;
        System.out.println("*******************开始ischeckOnOff******************");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        System.out.println("test1===" + sdf.format(new Date()));
        try {
            Date date1=CalendarDate.addDate(new Date(),"hour",-1); //只拿这一小时的数据
            QueryWrapper<FeeVo> wrapper = new QueryWrapper<>();
            //wrapper.gt("offdate", date1);
           // wrapper.lt("offdate", new Date());
            wrapper.and(wra -> wra.and(wra1->wra1.gt("dueamount", 0).eq("onoff",1).gt("offdate", date1).lt("offdate", new Date())).or(wra2->wra2.eq("dueamount", 0).eq("onoff",0)));
            // wrapper.and(wra -> wra.gt("dueallamount", 0).eq("onoff",1).or().eq("dueallamount", 0).eq("onoff",0));
            List<FeeVo> feeList = feeService.searchView(wrapper,new Page<>(1,99999));
            if(feeList.size()==0) return;
            for (FeeVo item1 : feeList) {
                boolean b=false;
                if (item1.getDueAmount()>0 && item1.getOnoff()==1) {
                    //欠费了，要断电
                    b = logicService.onOff(item1.getShopId(), 0, 0, -1,1);
                } else if (item1.getDueAmount() == 0 && item1.getOnoff()==0) {
                    //没欠费了，恢复送电
                    b = logicService.onOff(item1.getShopId(), 1, 0, -1,1);
                }
            }

        } catch (Exception ex) {
            logger.error("检查是否有开关异常：" + ex.getMessage());
        } finally {
            ischeckOnOff = true;
        }
        //System.out.println("*******************结束ischeckDelay******************");
    }

    /***
     * 检查是否有需要延迟开关的
     * 1分钟执行一次
     * @return
     */
     @Scheduled(cron = "0 0/10 * * * ?")
    public void checkDelay() {
        if (!ischeckDelay) return;
        ischeckDelay = false;
        System.out.println("*******************开始ischeckDelay******************");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        System.out.println("test1===" + sdf.format(new Date()));
        try {
            Date date1=CalendarDate.addDate(new Date(),"day",-1); //超过一天就去掉不要了
            QueryWrapper<ShopVo> wrapper = new QueryWrapper<>();
            wrapper.eq("state", 1);
            wrapper.isNotNull("delayTime");
            wrapper.isNotNull("delayOnOff");
            wrapper.and(wra -> wra.le("delayTime", new Date()));
            List<ShopVo> shopList = shopService.searchView(wrapper,new Page<>(1,99999));
            if (shopList.size() == 0) return;
            for (ShopVo item1 : shopList) {
                boolean b=false;
                if (item1.getDelayOnOff() == 1 && item1.getDueallamount()<=0) {
                    //如果是恢复送电，先看有没有欠费，有就不送电了
                      b = logicService.onOff(item1.getId(), item1.getDelayOnOff(), 0, -1,1);
                } else if (item1.getDelayOnOff() == 0 && item1.getDueallamount()>0) {
                    //如果是恢复断电，看下有没有欠费，如果交清了 就不要断电了
                      b = logicService.onOff(item1.getId(), item1.getDelayOnOff(), 0, -1,1);
                }
                else if (item1.getDelayTime().before(date1))
                {
                    //如果这个时间已经超过一天前就要执行的命令，那就去掉，说明是以前设置不需要执行的
                    b=true;
                }

                if (b) {
                    shopService.update(new UpdateWrapper<Shop>().set("delayOnOff",null).set("delayTime",null).eq("id",item1.getId()));
                }
            }
        } catch (Exception ex) {
            logger.error("检查是否有需要延迟开关异常：" + ex.getMessage());
        } finally {
            ischeckDelay = true;
        }
        //System.out.println("*******************结束ischeckDelay******************");
    }
    /***
     * 检查是否有欠费的，有要通知,一天运行一次
     * 10分钟执行一次
     * 0 0-5 14 * * ? 每天14:00至14:05每分钟一次触发
     * "0 15 10 ? * *"    每天早上10：15触发
     * @return
     */
     @Scheduled(cron = "0 30 8 ? * *")
    //@Scheduled(cron = "0/10 * * * * ?")
    public void checkMessageShop() {
        if (!ischeckMessageShop) return;
        ischeckMessageShop = false;
        System.out.println("*******************开始checkMessageShop******************");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        System.out.println("checkMessageShop===" + sdf.format(new Date()));
        try {
            //查询是否有欠费，而且发送通知是今天的
            QueryWrapper<FeeVo> wrapper = new QueryWrapper<>();
            wrapper.gt("dueAmount", 0);
            wrapper.isNotNull("openId");
            wrapper.and(wra -> wra.eq("sendDate1", CalendarDate.getDate("today"))
                    .or().eq("sendDate2", CalendarDate.getDate("today"))
                    .or().eq("sendDate3", CalendarDate.getDate("today")));
            List<FeeVo> feeList = feeService.searchView(wrapper, new Page<>(1, 99999));
            if (feeList.size() == 0) return;
            MessageData message;
            MessageDataItem messageitem;
            for (FeeVo item1 : feeList) {
                //发送通知
                message=new MessageData();
                messageitem= new MessageDataItem();
                messageitem.setColor("#173177");
                messageitem.setValue("尊敬的用户，您有新的欠费通知，请及时缴纳！");
                message.setFirst(messageitem);

                messageitem= new MessageDataItem();
                messageitem.setColor("#173177");
                messageitem.setValue(item1.getPerson());
                message.setKeyword1(messageitem);

                messageitem= new MessageDataItem();
                messageitem.setColor("#173177");
                messageitem.setValue(item1.getShopName());
                message.setKeyword2(messageitem);

                messageitem= new MessageDataItem();
                messageitem.setColor("#173177");
                messageitem.setValue(item1.getDueAmount().toString());
                message.setKeyword3(messageitem);

                messageitem= new MessageDataItem();
                messageitem.setColor("#173177");
                messageitem.setValue(sdf.format(item1.getOffDate()));
                message.setKeyword4(messageitem);

                messageitem= new MessageDataItem();
                messageitem.setColor("#173177");
                messageitem.setValue("请尽快缴纳，如有疑问，请咨询物业管理处");
                message.setRemark(messageitem);

                boolean b = logicService.sendMessage(item1.getOpenId(), message);
                if(b)
                {
                    Integer num=item1.getMessageNum()+1;
                    feeService.update(new UpdateWrapper<Fee>().set("messageNum",num).eq("id",item1.getId()));
                }
            }

        } catch (Exception ex) {
            logger.error("检查发送通知异常：" + ex.getMessage());
        } finally {
            ischeckMessageShop = true;
        }
        //System.out.println("*******************结束ischeckDelay******************");
    }

}

